'use strict'

var path = require('path')

var http = require('http')

var userModel = require('../models/user')

exports.login = async function(ctx,next){

  var reqBody = ctx.request.body

  var username = reqBody.username,
    password = reqBody.password,
    gotoPath = reqBody.gotoPath

  if (userModel.checkUser(username,password)) {
    // set cookie path `/` (root path of the domain)，ssocookie:sso
    ctx.cookies.set('ssocookie','sso') // default:root path
    await ctx.render(gotoPath,{title:`${gotoPath}登陆成功`})
  } else {
    await ctx.render('error',{title:'登陆失败',msg:'错误的用户名或者密码'})
  }
}

exports.renderDemo1 = exports.renderDemo2 = async function(ctx,next) {
  // console.log('originalUrl',ctx.originalUrl,'url',ctx.url,'path',ctx.path)
  var originalUrl = path.parse(ctx.url).base
  if ( ctx.cookies.get('ssocookie') === 'sso') await ctx.render(originalUrl,{title:originalUrl + '登陆成功'})
  else await ctx.render('login',{ title: '请登录', gotoPath: originalUrl})
}

exports.sameFatherLogin = async function(ctx,next) {

  var username = reqBody.username,
    password = reqBody.password,
    gotoUrl = reqBody.gotoUrl

  if (userModel.checkUser(username,password)) {
    // 同父域SSO的关键，将cookie设置到父域，这样子域即可访问父域cookie
    ctx.cookies.set('ssocookie','sso',{domain:'.x.com',path:'/test'})
    await ctx.render(gotoUrl,{title:'登陆成功'})
  } else {
    await ctx.render('error',{title:'登陆失败',msg:'错误的用户名或者密码'})
  }
}

exports.sameFatherRenderDemo = async function(ctx,next){
  var cookieName = 'ssocookie',
  cookieValue = ctx.cookies.get(cookieName)
  if (cookieValue) {
    // 向校验服务器提交cookie
    let checkUrl = `http://check.x.com/sso2/checkCookie?cookieName=${cookieName}&cookieValue=${cookieValue}`
    let success = await http.get(checkUrl)
    if (success) return await render('success') 
  }
  await // demo1和demo2登陆页
}

exports.checkCookie = async function(ctx,next){
  if (ctx.query.cookieName == 'ssocookie' && ctx.query.cookieValue == 'sso') ctx.body = true
  else ctx.body = false  
}